﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Framework.Common;
using Dal.Entities;
using PDFHelper.Helper;
namespace Web.Controllers
{

    [MyAuthAttribute(Role = 0)]
    [ValidateInput(false)]
    public class DocController : Controller
    {
        int docid;
        string status = string.Empty;
        Framework.Data.IRepository rep;

        public DocController()
        {
            rep = Framework.Data.RepositoryFactory.GetRepository();
            docid = TypeConvertHelper.StrToInt(System.Web.HttpContext.Current.Request["docid"], 0);
            ViewBag.DocID = docid;
            ViewBag.Status = System.Web.HttpContext.Current.Request["status"] ?? "edit";
        }

        public ActionResult AddBaseInfo()
        {
            Dal.Entities.Doc doc = new Dal.Entities.Doc
            {
                StatusAudit = 0,
                StatusComplete = 0,
                StatusQuestion = 0,
                StatusValid = 1,
                TimeAdd = DateTime.Now,
                UserID = Common.GetUserID()
            };

            rep.Add(doc);
            rep.Save();

            rep.Add(new Doc0 { DocID = doc.DocID });
            rep.Add(new Doc1 { DocID = doc.DocID });
            rep.Add(new Doc2 { DocID = doc.DocID });
            rep.Add(new Doc3 { DocID = doc.DocID });
            rep.Add(new Doc4 { DocID = doc.DocID });
            if (rep.Save() > 0)
            {
                return RedirectToAction("edit0", new { docid = doc.DocID });
            }
            return null;
        }
        #region edit0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult edit0()
        {
            var Doc0 = rep.GetByKey<Dal.Entities.Doc0>(docid);
            return View(Doc0);
        }
        /// <summary>
        /// 只保存不跳转
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult edit0(FormCollection form, string buttonsave, string auditbutton)
        {
            if (!string.IsNullOrWhiteSpace(auditbutton))
            {
                int audit = TypeConvertHelper.StrToInt(auditbutton);
                Doc0 docAudit = new Doc0 { DocID = docid, StatusAudit = -1 };
                ViewBag.Result = rep.AttachThenSaveChange(docAudit, i => i.StatusAudit = audit);
                Common.SetAudit(docid);
                Common.AlertRedirect("操作成功", "/doc/edit1?status=audit&docid=" + docid);
                return new EmptyResult();
            }
            var Doc0 = rep.GetByKey<Dal.Entities.Doc0>(docid);
            rep.Attach(Doc0);
            TryUpdateModel<Dal.Entities.Doc0>(Doc0);
            Doc0.StatusComplete = CheckComplete(Doc0.InputTime, Doc0.PatientName, Doc0.PatientTel) ? 1 : 0;

            ViewBag.Result = rep.Save() > 0;
            Common.SetComplete(docid);
            Common.SetAudit(docid);
            if (buttonsave != null)
            {
                Common.AlertRedirect("操作成功", "/doc/edit0?docid=" + docid);
                return new EmptyResult();
            }
            else
            {
                if (Request["buttonquestion"] != null)
                {
                    Common.UpdateModifyStatus(docid);
                }
                return RedirectToAction("edit1", new { docid = docid }); //(Doc0);
            }
        }
        #endregion

        [HttpGet]
        public ActionResult Edit1()
        {
            var doc1 = rep.GetByKey<Doc1>(docid);
            return View(doc1);
        }

        [HttpPost]
        public ActionResult Edit1(FormCollection form, string buttonsave, string auditbutton
            , string[] AdditionReason
            , string[] AdditionReason2Detail
            , string[] AdditionReason3Detail
            , string[] Symptom
            )
        {
            if (!string.IsNullOrWhiteSpace(auditbutton))
            {
                int audit = TypeConvertHelper.StrToInt(auditbutton);
                Doc1 docAudit = new Doc1 { DocID = docid, StatusAudit = -1 };
                ViewBag.Result = rep.AttachThenSaveChange(docAudit, i => i.StatusAudit = audit);
                Common.SetAudit(docid);
                Common.AlertRedirect("操作成功", "/doc/edit2?status=audit&docid=" + docid);
                return new EmptyResult();
            }
            var doc1 = rep.GetByKey<Doc1>(docid);
            rep.Attach(doc1);
            TryUpdateModel<Doc1>(doc1);
            doc1.AdditionReason = GetStringFromArray(AdditionReason);
            doc1.AdditionReason2Detail = GetStringFromArray(AdditionReason2Detail);
            doc1.AdditionReason3Detail = GetStringFromArray(AdditionReason3Detail);
            doc1.Symptom = GetStringFromArray(Symptom);
            doc1.StatusComplete = CheckComplete(
                doc1.IsFirstTime,
                doc1.Symptom,
                doc1.JiaolvFollow
                ) ? 1 : 0;
            ViewBag.Result = rep.Save() > 0;
            Common.SetComplete(docid);
            Common.SetAudit(docid);
            if (buttonsave != null)
            {
                Common.AlertRedirect("操作成功", "/doc/edit1?docid=" + docid);
                return new EmptyResult();
            }
            else
            {
                if (Request["buttonquestion"] != null)
                {
                    Common.UpdateModifyStatus(docid);
                }
                return RedirectToAction("Edit2", new { docid = docid });
            }
        }

        [HttpGet]
        public ActionResult Edit2()
        {
            var doc2 = rep.GetByKey<Doc2>(docid);
            #region  脱落
            var t2 = DateTime.Now.AddDays(-14);
            var tlt2 = t2.AddDays(-14);
            var doc0 = rep.GetByKey<Doc0>(docid);
            ViewBag.TuoLuo = false;// doc2.StatusComplete == 0 && doc0.InputTime < tlt2;
            ViewBag.BeforeSuiFang = false;// !doc0.InputTime.HasValue || doc0.InputTime > t2;
            #endregion
            return View(doc2);
        }

        [HttpPost]
        public ActionResult Edit2(FormCollection form
            , string buttonsave
            , string auditbutton
            )
        {
            if (!string.IsNullOrWhiteSpace(auditbutton))
            {
                int audit = TypeConvertHelper.StrToInt(auditbutton);
                Doc2 docAudit = new Doc2 { DocID = docid, StatusAudit = -1 };
                ViewBag.Result = rep.AttachThenSaveChange(docAudit, i => i.StatusAudit = audit);
                Common.SetAudit(docid);
                Common.AlertRedirect("操作成功", "/doc/edit3?status=audit&docid=" + docid);
                return new EmptyResult();
            }

            var doc2 = rep.GetByKey<Doc2>(docid);
            rep.Attach(doc2);
            TryUpdateModel(doc2);
            doc2.StatusComplete = CheckComplete(doc2.VisitDateDoc2, doc2.DoseDoc2, doc2.Remit5C6Doc2, doc2.PHQ9C10Doc2, doc2.SuggestDoc2) ? 1 : 0;
            doc2.VisitorID = Common.GetUserID();
            ViewBag.Result = rep.Save() > 0;
            Common.SetComplete(docid);
            Common.SetAudit(docid);
            if (buttonsave != null)
            {
                Common.AlertRedirect("操作成功", "/doc/edit2?docid=" + docid);
                return new EmptyResult();
            }
            else
            {
                if (Request["buttonquestion"] != null)
                {
                    Common.UpdateModifyStatus(docid);
                }
                return RedirectToAction("Edit3", new { docid = docid });
            }
        }


        [HttpGet]
        public ActionResult Edit3()
        {
            var doc3 = rep.GetByKey<Doc3>(docid);
            #region  脱落
            var t3 = DateTime.Now.AddDays(-56);
            var tlt3 = t3.AddDays(-14);
            var doc0 = rep.GetByKey<Doc0>(docid);
            ViewBag.TuoLuo = false;// doc3.StatusComplete == 0 && doc0.InputTime < tlt3;
            ViewBag.BeforeSuiFang = false;//!doc0.InputTime.HasValue || doc0.InputTime > t3;
            #endregion
            return View(doc3);
        }

        [HttpPost]
        public ActionResult Edit3(FormCollection form
            , string buttonsave
            , string auditbutton
            )
        {
            if (!string.IsNullOrWhiteSpace(auditbutton))
            {
                int audit = TypeConvertHelper.StrToInt(auditbutton);
                Doc3 docAudit = new Doc3 { DocID = docid, StatusAudit = -1 };
                ViewBag.Result = rep.AttachThenSaveChange(docAudit, i => i.StatusAudit = audit);
                Common.SetAudit(docid);
                Common.AlertRedirect("操作成功", "/doc/edit4?status=audit&docid=" + docid);
                return new EmptyResult();
            }

            var doc3 = rep.GetByKey<Doc3>(docid);
            rep.Attach(doc3);
            TryUpdateModel(doc3);
            doc3.StatusComplete = CheckComplete(doc3.VisitDateDoc3, doc3.DoseDoc3, doc3.Remit5C6Doc3, doc3.PHQ9C10Doc3, doc3.SuggestDoc3) ? 1 : 0;
            doc3.VisitorID = Common.GetUserID();
            ViewBag.Result = rep.Save() > 0;
            Common.SetComplete(docid);
            Common.SetAudit(docid);
            if (buttonsave != null)
            {
                Common.AlertRedirect("操作成功", "/doc/edit3?docid=" + docid);
                return new EmptyResult();
            }
            else
            {
                if (Request["buttonquestion"] != null)
                {
                    Common.UpdateModifyStatus(docid);
                }
                return RedirectToAction("Edit4", new { docid = docid });
            }
        }


        [HttpGet]
        public ActionResult Edit4()
        {
            var doc4 = rep.GetByKey<Doc4>(docid);
            #region  脱落
            var t4 = DateTime.Now.AddDays(-56);
            var tlt4 = t4.AddDays(-14);
            var doc0 = rep.GetByKey<Doc0>(docid);
            ViewBag.TuoLuo = false;// doc4.StatusComplete == 0 && doc0.InputTime < tlt4;
            ViewBag.BeforeSuiFang = false;//!doc0.InputTime.HasValue || doc0.InputTime > t4;
            #endregion
            return View(doc4);
        }

        [HttpPost]
        public ActionResult Edit4(FormCollection form
            , string buttonsave
            , string auditbutton
            )
        {
            if (!string.IsNullOrWhiteSpace(auditbutton))
            {
                int audit = TypeConvertHelper.StrToInt(auditbutton);
                Doc4 docAudit = new Doc4 { DocID = docid, StatusAudit = -1 };
                ViewBag.Result = rep.AttachThenSaveChange(docAudit, i => i.StatusAudit = audit);
                Common.SetAudit(docid);
                Common.AlertRedirect("操作成功", "/doc/manage");
                return new EmptyResult();
            }

            var doc4 = rep.GetByKey<Doc4>(docid);
            rep.Attach(doc4);
            TryUpdateModel(doc4);
            doc4.StatusComplete = CheckComplete(doc4.VisitDateDoc4, doc4.DoseDoc4, doc4.Remit5C6Doc4, doc4.PHQ9C10Doc4, doc4.SuggestDoc4) ? 1 : 0;
            doc4.VisitorID = Common.GetUserID();
            ViewBag.Result = rep.Save() > 0;
            Common.SetComplete(docid);
            Common.SetAudit(docid);
            if (buttonsave != null)
            {
                Common.AlertRedirect("操作成功", "/doc/edit4?docid=" + docid);
                return new EmptyResult();
            }
            else
            {
                if (Request["buttonquestion"] != null)
                {
                    Common.UpdateModifyStatus(docid);
                }
                return RedirectToAction("manage");
            }
        }


        public ActionResult Manage()
        {
            QueryModel query = new QueryModel();
            TryUpdateModel(query);
            int pageindex = TypeConvertHelper.StrToInt(Request["pageindex"], 1);
            IQueryable<DocForShow> list = null;

            list = from doc in rep.GetQuery<Doc>()
                   join user in rep.GetQuery<User>()
                   on doc.UserID equals user.ID
                   join Doc0 in rep.GetQuery<Doc0>()
                   on doc.DocID equals Doc0.DocID
                   join doc1 in rep.GetQuery<Doc1>()
                   on doc.DocID equals doc1.DocID
                   join doc2 in rep.GetQuery<Doc2>()
                   on doc.DocID equals doc2.DocID
                   join doc3 in rep.GetQuery<Doc3>()
                   on doc.DocID equals doc3.DocID
                   join doc4 in rep.GetQuery<Doc4>()
                   on doc.DocID equals doc4.DocID
                   where doc.StatusValid >= 1
                   select new DocForShow
                   {
                       doc = doc,
                       Doc0 = Doc0,
                       doc1 = doc1,
                       doc2 = doc2,
                       doc3 = doc3,
                       doc4 = doc4,
                       username = user.UserName
                   };
            if (Common.GetUserRole() == 0)
            {
                int userid = Common.GetUserID();
                list = list.Where(i => i.doc.UserID == userid);
            }
            if (query.StatusSuiFang.HasValue)
            {
                switch (query.StatusSuiFang.Value)
                {
                    case 2:
                        {
                            var t2 = DateTime.Now.AddDays(-14);
                            var tlt2 = t2.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc2.StatusComplete == 0 && i.Doc0.InputTime < t2 && i.Doc0.InputTime > tlt2);
                            break;
                        }
                    case 8:
                        {
                            var t8 = DateTime.Now.AddDays(-56);
                            var tlt8 = t8.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc3.StatusComplete == 0 && i.Doc0.InputTime < t8 && i.Doc0.InputTime > tlt8);
                            break;
                        }
                    case 24:
                        {
                            var t24 = DateTime.Now.AddDays(-56);
                            var tlt24 = t24.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc4.StatusComplete == 0 && i.Doc0.InputTime < t24 && i.Doc0.InputTime > tlt24);
                            break;
                        }
                    case -100:
                        {
                            list = list.Where(i => i.doc.StatusValid == 2);
                            //var t2 = DateTime.Now.AddDays(-14);
                            //var tlt2 = t2.AddDays(-14);

                            //var t8 = DateTime.Now.AddDays(-56);
                            //var tlt8 = t8.AddDays(-14);

                            //var t24 = DateTime.Now.AddDays(-56);
                            //var tlt24 = t24.AddDays(-14);

                            //list = list.Where(i => (
                            //    (i.doc2.StatusComplete == 0 && i.Doc0.InputTime < tlt2) ||
                            //    (i.doc3.StatusComplete == 0 && i.Doc0.InputTime < tlt8) ||
                            //    (i.doc4.StatusComplete == 0 && i.Doc0.InputTime < tlt24)
                            //    ));

                            break;
                        }
                }
            }
            if (query.DocNO.HasValue)
            {
                list = list.Where(i => i.doc.DocID == query.DocNO.Value);
            }
            if (!string.IsNullOrEmpty(query.UserName))
            {
                var user = rep.First<User>(i => i.UserName == query.UserName);
                if (user != null)
                {
                    list = list.Where(i => i.doc.UserID == user.ID);
                }
            }
            if (query.InputStart.HasValue)
            {
                list = list.Where(i => i.doc.TimeAdd >= query.InputStart.Value);
            }
            if (query.InputEnd.HasValue)
            {
                list = list.Where(i => i.doc.TimeAdd <= query.InputEnd.Value);
            }
            if (query.InGroupStart.HasValue)
            {
                list = list.Where(i => i.Doc0.InputTime >= query.InGroupStart.Value);
            }
            if (query.InGroupEnd.HasValue)
            {
                list = list.Where(i => i.Doc0.InputTime <= query.InGroupEnd.Value);
            }
            if (query.AuditStart.HasValue)
            {
                list = list.Where(i => i.doc.TimeAudit >= query.AuditStart);
            }
            if (query.AuditEnd.HasValue)
            {
                list = list.Where(i => i.doc.TimeAudit <= query.AuditEnd);
            }
            if (query.StatusComplete.HasValue && query.StatusComplete.Value != -1)
            {
                if (query.StatusComplete == 2) //完全空白病历
                {
                    list = list.Where(i => i.doc.StatusComplete == 0
                        && i.Doc0.StatusComplete == 0
                        && i.doc1.StatusComplete == 0
                        && i.doc2.StatusComplete == 0
                        && i.doc3.StatusComplete == 0
                        && i.doc4.StatusComplete == 0);
                }
                else
                {
                    list = list.Where(i => i.doc.StatusComplete == query.StatusComplete.Value);
                }
            }
            if (query.StatusAudit.HasValue && query.StatusAudit.Value != -1)
            {
                if (query.StatusAudit.Value == 0)
                {
                    list = list.Where(i => i.doc.StatusAudit == 0);
                }
                else if (query.StatusAudit.Value == 1)
                {
                    list = list.Where(i => i.doc.StatusAudit >= 1);
                }
            }
            if (query.StatusQuestion.HasValue && query.StatusQuestion.Value != -1)
            {
                list = list.Where(i => i.doc.StatusQuestion == query.StatusQuestion.Value);
            }
            if (query.StatusQuestionReply.HasValue && query.StatusQuestionReply.Value != -1)
            {
                list = list.Where(i => i.doc.StatusModify == query.StatusQuestionReply.Value);
            }
            ViewBag.RecordCount = list.Count();
            ViewBag.PageIndex = pageindex;
            list = list.OrderByDescending(i => i.doc.DocID).Skip((pageindex - 1) * 10).Take(10);
            ViewBag.Record = list.ToList();
            return View(query);
            //return View(query);

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="docID"></param>
        /// <returns></returns>
        [MyAuth(Role = 0)]
        public ActionResult Delete()
        {
            rep.Attach(new Dal.Entities.Doc());
            Dal.Entities.Doc doc = new Doc { DocID = docid, StatusValid = -1 };
            rep.AttachThenSaveChange(doc, i => i.StatusValid = 0);
            string requestUrl = Request["url"];
            if (!string.IsNullOrWhiteSpace(requestUrl))
            {
                Common.AlertRedirect("删除成功", requestUrl);
            }
            else
            {
                Common.AlertRedirect("删除成功", "/doc/manage");
            }
            return null;
        }


        public ActionResult Question(string field, int type, string description)
        {
            if (Request.HttpMethod.ToLower() == "post")
            {
                if (Request["close"] != null)//关闭
                {
                    var list = rep.Get<DocQuestion>(i => i.DocID == docid && i.FieldName == field && i.Type == type && i.Status == 0);
                    if (list != null)
                    {
                        foreach (var q in list)
                        {
                            rep.AttachThenSaveChange(q, i => i.Status = 1);
                        }
                        Common.UpdateQuestionStatus(docid);
                    }
                }
                else if (Request["submit"] != null)//提交信息
                {
                    string questionContent = Request["QContent"];
                    if (!string.IsNullOrEmpty(questionContent))
                    {
                        rep.AddThenSaveChange(new DocQuestion
                        {
                            DocID = docid,
                            FieldName = field,
                            Status = 0,//默认值是0
                            Type = type,
                            QContent = questionContent,
                            OperateTime = DateTime.Now,
                            OperateUserID = Common.GetUserID()
                        });
                        Common.UpdateQuestionStatus(docid);
                    }
                }
            }
            ViewBag.Param = new { field = field, type = type, description = description, docid = docid };
            var allquestion = rep.Get<DocQuestion>(i => i.DocID == docid && i.FieldName == field && i.Type == type);
            ViewBag.Question = allquestion.Where(i => i.Status == 0).ToList();
            ViewBag.QuestionClose = allquestion.Where(i => i.Status == 1).ToList();
            ViewBag.Description = description;
            return View(new DocQuestion { DocID = docid, FieldName = field, Type = type });
        }

        public ActionResult Export(int DocID)
        {
            string url = System.Configuration.ConfigurationManager.AppSettings["host"] + "/preview?docid=" + DocID;
            string exeFile = Server.MapPath("~/lib/wkhtmltopdf/wkhtmltopdf.exe");
            string savePath = Server.MapPath("~/Pdf/" + DocID + ".pdf");
            if (TextSharpHelper.HtmlToPdf(exeFile, url, savePath))
            {
                return File(savePath, "application/pdf", "病历NO" + DocID + ".pdf");
            }
            return new EmptyResult();
        }

        [NonAction]
        private string GetStringFromArray(string[] array)
        {
            return array == null ? null : string.Join(",", array);
        }

        [NonAction]
        private bool CheckComplete(params object[] objs)
        {
            return objs.Count(i => i == null) == 0 ? true : false;
        }



        #region excel 导出
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportExcel(QueryModel model)
        {
            QueryModel query = model;
            IQueryable<DocForShow> list = null;

            list = from doc in rep.GetQuery<Doc>()
                   join user in rep.GetQuery<User>()
                   on doc.UserID equals user.ID
                   join Doc0 in rep.GetQuery<Doc0>()
                   on doc.DocID equals Doc0.DocID
                   join doc1 in rep.GetQuery<Doc1>()
                   on doc.DocID equals doc1.DocID
                   join doc2 in rep.GetQuery<Doc2>()
                   on doc.DocID equals doc2.DocID
                   join doc3 in rep.GetQuery<Doc3>()
                   on doc.DocID equals doc3.DocID
                   join doc4 in rep.GetQuery<Doc4>()
                   on doc.DocID equals doc4.DocID
                   where doc.StatusValid >= 1
                   select new DocForShow
                   {
                       doc = doc,
                       Doc0 = Doc0,
                       doc1 = doc1,
                       doc2 = doc2,
                       doc3 = doc3,
                       doc4 = doc4,
                       User = user,
                       username = user.UserName
                   };

            if (query.DocNO.HasValue)
            {
                list = list.Where(i => i.doc.DocID == query.DocNO.Value);
            }

            if (Common.Admin())
            {
                if (!string.IsNullOrEmpty(query.UserName))
                {
                    var user = rep.First<User>(i => i.UserName == query.UserName);
                    if (user != null)
                    {
                        list = list.Where(i => i.doc.UserID == user.ID);
                    }
                    else
                    {
                        Common.AlertRedirect("未搜索到数据", "/doc/exportmanage");
                        return View(query);
                    }
                }
            }
            else
            {
                int currentUserID = Common.GetUserID();
                list = list.Where(i => i.doc.UserID == currentUserID);
            }
            if (query.StatusSuiFang.HasValue)
            {
                switch (query.StatusSuiFang.Value)
                {
                    case 2:
                        {
                            var t2 = DateTime.Now.AddDays(-14);
                            var tlt2 = t2.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc2.StatusComplete == 0 && i.Doc0.InputTime < t2 && i.Doc0.InputTime > tlt2);
                            break;
                        }
                    case 8:
                        {
                            var t8 = DateTime.Now.AddDays(-56);
                            var tlt8 = t8.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc3.StatusComplete == 0 && i.Doc0.InputTime < t8 && i.Doc0.InputTime > tlt8);
                            break;
                        }

                    case 24:
                        {
                            var t24 = DateTime.Now.AddDays(-56);
                            var tlt24 = t24.AddDays(-14);
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc4.StatusComplete == 0 && i.Doc0.InputTime < t24 && i.Doc0.InputTime > tlt24);
                            break;
                        }
                    case -2:
                        {
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc2.StatusComplete == 1);
                            break;
                        }
                    case -8:
                        {
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc3.StatusComplete == 1);
                            break;
                        }
                    case -24:
                        {
                            list = list.Where(i => i.doc.StatusValid == 1 && i.doc4.StatusComplete == 1);
                            break;
                        }
                    case -100:
                        {
                            list = list.Where(i => i.doc.StatusValid == 2);
                            break;
                        }

                }
            }
            if (!string.IsNullOrEmpty(query.UserName))
            {
                var user = rep.First<User>(i => i.UserName == query.UserName);
                if (user != null)
                {
                    list = list.Where(i => i.doc.UserID == user.ID);
                }
            }
            if (query.InputStart.HasValue)
            {
                list = list.Where(i => i.doc.TimeAdd >= query.InputStart.Value);
            }
            if (query.InputEnd.HasValue)
            {
                list = list.Where(i => i.doc.TimeAdd <= query.InputEnd.Value);
            }
            if (query.InGroupStart.HasValue)
            {
                list = list.Where(i => i.Doc0.InputTime >= query.InGroupStart.Value);
            }
            if (query.InGroupEnd.HasValue)
            {
                list = list.Where(i => i.Doc0.InputTime <= query.InGroupEnd.Value);
            }
            if (query.AuditStart.HasValue)
            {
                list = list.Where(i => i.doc.TimeAudit >= query.AuditStart);
            }
            if (query.AuditEnd.HasValue)
            {
                list = list.Where(i => i.doc.TimeAudit <= query.AuditEnd);
            }
            if (query.StatusComplete.HasValue && query.StatusComplete.Value != -1)
            {
                list = list.Where(i => i.doc.StatusComplete == query.StatusComplete.Value);
            }
            if (query.StatusAudit.HasValue && query.StatusAudit.Value != -1)
            {
                switch (query.StatusAudit.Value)
                {
                    case 0:
                        list = list.Where(i => i.doc.StatusAudit == 0);
                        break;

                    case 1:
                        list = list.Where(i => i.doc.StatusAudit >= 1);
                        break;

                    case 2: //2周已审核
                        list = list.Where(i => i.doc2.StatusAudit >= 1);
                        break;

                    case 3: //8周已审核
                        list = list.Where(i => i.doc3.StatusAudit >= 1);
                        break;

                    case 4: //6个月已审核
                        list = list.Where(i => i.doc4.StatusAudit >= 1);
                        break;
                }
            }
            if (query.StatusQuestion.HasValue && query.StatusQuestion.Value != -1)
            {
                list = list.Where(i => i.doc.StatusQuestion == query.StatusQuestion.Value);
            }
            if (query.StatusQuestionReply.HasValue && query.StatusQuestionReply.Value != -1)
            {
                list = list.Where(i => i.doc.StatusModify == query.StatusQuestionReply.Value);
            }
            var result = list.ToList();
            if (result != null && result.Count > 0)
            {
                ResponseExcel();
                ViewBag.Record = list.ToList();
            }
            else
            {
                Common.AlertRedirect("未搜索到数据", "/doc/exportmanage");
            }
            return View(query);

        }
        private void ResponseExcel()
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportManage()
        {
            return View();
        }
        #endregion

    }

    #region entity
    /// <summary>
    /// 
    /// </summary>
    public class QueryModel
    {
        public int? DocNO { get; set; }
        public string UserName { get; set; }
        public DateTime? InputStart { get; set; }
        public DateTime? InputEnd { get; set; }
        public int? StatusComplete { get; set; }
        public int? StatusAudit { get; set; }
        public int? StatusQuestion { get; set; }
        public DateTime? AuditStart { get; set; }
        public DateTime? AuditEnd { get; set; }

        public DateTime? InGroupStart { get; set; }
        public DateTime? InGroupEnd { get; set; }
        /// <summary>
        /// 回应质疑
        /// </summary>
        public int? StatusQuestionReply { get; set; }
        /// <summary>
        /// 随访状态
        /// </summary>
        public int? StatusSuiFang { get; set; }
    }
    /// <summary>
    /// 
    /// </summary>
    public class DocForShow
    {
        public Doc doc { get; set; }
        public string username { get; set; }

        #region export

        public Doc0 Doc0 { get; set; }
        public Doc1 doc1 { get; set; }
        public Doc2 doc2 { get; set; }
        public Doc3 doc3 { get; set; }
        public Doc4 doc4 { get; set; }
        public User User { get; set; }
        string desc2, desc8, desc24;
        bool HasTuoluo = false;
        public string Desc2
        {
            get
            {
                if (string.IsNullOrWhiteSpace(desc2))
                {
                    if (doc2.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-14).AddDays(-14))
                    {
                        HasTuoluo = true;
                        desc2 = "<a style=\"color:#dc500c\" href=\"javascript:;\" title=\"脱落日期:" + Doc0.InputTime.Value.AddDays(21).ToString("yyyy-MM-dd") + "\">脱落</a>";
                    }
                    else if (doc2.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-14))
                    {
                        desc2 = "<span style=\"color:#420c82\">待随访</span>";
                    }
                    else if (doc2.StatusComplete == 1)
                    {
                        desc2 = Common.GetDoctorName(doc2.VisitorID);
                    }
                }
                return desc2;
            }
            set
            {
                desc2 = value;
            }
        }
        public string Desc8
        {
            get
            {
                if (HasTuoluo) return string.Empty;
                if (string.IsNullOrWhiteSpace(desc8))
                {
                    if (doc3.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-56).AddDays(-14))
                    {
                        HasTuoluo = true;
                        desc8 = "<a style=\"color:#dc500c\" href=\"javascript:;\" title=\"脱落日期:" + Doc0.InputTime.Value.AddDays(63).ToString("yyyy-MM-dd") + "\">脱落</a>";
                    }
                    else if (doc3.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-56))
                    {
                        desc8 = "<span style=\"color:#420c82\">待随访</span>";
                    }
                    else if (doc3.StatusComplete == 1)
                    {
                        desc8 = Common.GetDoctorName(doc3.VisitorID);
                    }
                }
                return desc8;
            }
            set
            {
                desc8 = value;
            }
        }
        public string Desc24
        {
            get
            {
                if (HasTuoluo) return string.Empty;
                if (string.IsNullOrWhiteSpace(desc24))
                {
                    if (doc4.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-56).AddDays(-14))
                    {
                        HasTuoluo = true;
                        desc24 = "<a style=\"color:#dc500c\" href=\"javascript:;\" title=\"脱落日期:" + Doc0.InputTime.Value.AddMonths(6).AddDays(7).ToString("yyyy-MM-dd") + "\">脱落</a>";
                    }
                    else if (doc4.StatusComplete == 0 && Doc0.InputTime < DateTime.Now.AddDays(-56))
                    {
                        desc24 = "<span style=\"color:#420c82\">待随访</span>";
                    }
                    else if (doc4.StatusComplete == 1)
                    {
                        desc24 = Common.GetDoctorName(doc4.VisitorID);
                    }
                }

                return desc24;
            }
            set
            {
                desc24 = value;
            }
        }



        #endregion
    }

    #endregion
}
